<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="计划编号">
              <el-input v-model="queryParams.planNumber" placeholder="请输入计划编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="任务名称">
              <el-input v-model="queryParams.taskName" placeholder="请输入任务名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="盘点区域">
              <el-select v-model="queryParams.area" placeholder="请选择盘点区域" clearable>
                <el-option v-for="item in areaOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="状态">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option label="未开始" :value="0" />
                <el-option label="已完成" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4" style="text-align: left;">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="mt-1">
      <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>
        新增盘点
      </el-button>
      <el-table :data="inventoryList" border v-loading="loading" @selection-change="handleSelectionChange" class="mt-2">
        <el-table-column type="selection" align="center" />
        <el-table-column prop="planNumber" label="计划编号" align="center" />
        <el-table-column prop="taskName" label="任务名称" align="center" />
        <el-table-column prop="area" label="盘点区域" align="center">
          <template #default="{ row }">
            <el-tag>{{ getName(areaOptions, row.area, 'dictValue', 'dictLabel') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="planTime" label="计划时间" align="center" />
        <el-table-column prop="manager" label="负责人" align="center" />
        <el-table-column prop="status" label="状态" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '已完成' : '未开始' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="actualTime" label="实际时间" align="center" />
        <el-table-column prop="auditResult" label="盘点结果" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)" v-if="row.status == 0">
              编辑
            </el-button>
            <el-button size="small" type="success" @click="handleComplete(row)" v-if="row.status == 0">
              完成
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)" v-if="row.status == 0">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination class="mt-2" background layout="total, sizes, prev, pager, next, jumper" :total="total"
        v-model:page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="任务名称" prop="taskName" required>
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>

        <el-form-item label="盘点区域" prop="area" required>
          <el-select v-model="form.area" placeholder="请选择盘点区域" style="width: 100%" @change="handleAreaChange">
            <el-option v-for="item in areaOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>

        <el-form-item label="计划时间" prop="planTime" required>
          <el-date-picker v-model="form.planTime" type="datetime" placeholder="选择计划时间"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
        </el-form-item>

        <el-form-item label="负责人" prop="manager" required>
          <!-- <el-select v-model="form.manager" placeholder="请选择负责人" style="width: 100%">
            <el-option v-for="item in managerOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select> -->
          <el-input v-model="form.manager" placeholder="请输入负责人名称" />

        </el-form-item>

        <el-form-item label="设备清单" prop="deviceList" required>
          <div class="device-transfer-container">
            <div class="device-list">
              <div class="device-list-header">
                <span>可选设备</span>
                <span>{{ `${selectedDevices.length}/${deviceOptions.length}` }}</span>
              </div>
              <div class="device-list-content">
                <el-checkbox-group v-model="selectedDevices">
                  <el-checkbox v-for="item in deviceOptions" :key="item.id" :label="item.id" class="device-item">
                    {{ item.name }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>

            <div class="transfer-buttons">
              
              <el-button type="danger" :disabled="form.deviceList.length === 0" @click="removeAllDevices">
                <el-icon>
                  <ArrowLeft />
                </el-icon>
              </el-button>
              <el-button type="primary" :disabled="selectedDevices.length === 0" @click="addSelectedDevices">
                <el-icon>
                  <ArrowRight />
                </el-icon>
              </el-button>
            </div>

            <div class="device-list">
              <div class="device-list-header">
                <span>已选设备</span>
                <span>{{ `${form.deviceList.length}/${deviceOptions.length}` }}</span>
              </div>
              <div class="device-list-content">
                <el-empty v-if="form.deviceList.length === 0" description="No data" />
                <div v-else>
                  <div v-for="id in form.deviceList" :key="id" class="selected-device-item">
                    {{ getDeviceName(id) }}
                    <el-icon class="remove-icon" @click="removeDevice(id)">
                      <Close />
                    </el-icon>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialog.visible" :title="`盘点详情 - ${detailDialog.data.planNumber}`" width="800px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="计划编号">{{ detailDialog.data.planNumber }}</el-descriptions-item>
        <el-descriptions-item label="任务名称">{{ detailDialog.data.taskName }}</el-descriptions-item>
        <el-descriptions-item label="盘点区域">
          <el-tag>
            {{ getName(areaOptions, detailDialog.data.area, 'dictValue', 'dictLabel') }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="计划时间">{{ detailDialog.data.planTime }}</el-descriptions-item>
        <el-descriptions-item label="负责人">{{ detailDialog.data.manager }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detailDialog.data.status === 1 ? 'success' : 'info'">
            {{ detailDialog.data.status === 1 ? '已完成' : '未开始' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="实际时间">{{ detailDialog.data.actualTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="盘点结果">{{ detailDialog.data.auditResult || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ detailDialog.data.remark || '无' }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">盘点设备列表</el-divider>
      <el-table :data="detailDialog.data.deviceList" border>
        <el-table-column prop="equipmentId" label="设备编号" align="center" />
        <el-table-column prop="equipmentName" label="设备名称" align="center">

        </el-table-column>
        <el-table-column prop="equipmentType" label="设备类型" align="center">
          <template #default="{ row }">
            <el-tag>{{ getName(equipmentTypeOptions, row.equipmentType, 'dictValue', 'dictLabel') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="area" label="盘点区域" align="center">
          <template #default="{ row }">
            <el-tag>{{ getName(areaOptions, row.area, 'dictValue', 'dictLabel') }}</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 完成盘点对话框 -->
    <el-dialog v-model="completeDialog.visible" title="完成盘点" width="500px" :close-on-click-modal="false">
      <el-form ref="completeFormRef" :model="completeForm" :rules="completeRules" label-width="120px">
        <el-form-item label="盘点结果" prop="auditResult">
          <el-input v-model="completeForm.auditResult" type="textarea" :rows="3" placeholder="请输入盘点结果描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="completeDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitCompleteForm">确认完成</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getAreaList,
  getEquipmentTypeList,
  getDeviceList,
  listInventoryPlan,
  getInventoryPlanDetail,
  addInventoryPlan,
  updateInventoryPlan,
  completeInventoryPlan,
  deleteInventoryPlan
} from '@/api/prod_operate/device/asset_inventory/equipment_inventory'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  planNumber: '',
  taskName: '',
  area: '',
  status: undefined
})

// 表单数据
const form = reactive({
  id: undefined,
  taskName: '',
  area: '',
  planTime: '',
  manager: '',
  deviceList: [],
  remark: ''
})

// 完成盘点表单
const completeForm = reactive({
  id: undefined,
  auditResult: ''
})

// 对话框控制
const dialog = reactive({
  visible: false,
  title: ''
})

const detailDialog = reactive({
  visible: false,
  data: {}
})

const completeDialog = reactive({
  visible: false
})

// 下拉选项数据
const areaOptions = ref([])
const equipmentTypeOptions = ref([])
const deviceOptions = ref([])

// 表格数据
const inventoryList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const formRef = ref()
const completeFormRef = ref()


// 在setup()中添加以下代码
const selectedDevices = ref([]) // 临时选中的设备
const managerOptions = ref([
  { value: 'manager1', label: '张三' },
  { value: 'manager2', label: '李四' },
  { value: 'manager3', label: '王五' }
])

// 获取设备名称
const getDeviceName = (id) => {
  const device = deviceOptions.value.find(item => item.id === id)
  return device ? device.name : ''
}

// 添加选中的设备
const addSelectedDevices = () => {
  form.deviceList = [...new Set([...form.deviceList, ...selectedDevices.value])]
  selectedDevices.value = []
}

// 移除单个设备
const removeDevice = (id) => {
  form.deviceList = form.deviceList.filter(item => item !== id)
}

// 移除所有设备
const removeAllDevices = () => {
  form.deviceList = []
}

// 重置表单时清空选中设备
const resetForm = () => {
  form.deviceList = []
  selectedDevices.value = []
}
// 表单验证规则
const rules = reactive({
  taskName: [
    { required: true, message: '请输入任务名称', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请选择盘点区域', trigger: 'change' }
  ],
  planTime: [
    { required: true, message: '请选择计划时间', trigger: 'change' }
  ],
  manager: [
    { required: true, message: '请输入负责人', trigger: 'blur' }
  ],
  deviceList: [
    { required: true, message: '请选择盘点设备', trigger: 'change' }
  ]
})

const completeRules = reactive({
  auditResult: [
    { required: true, message: '请输入盘点结果', trigger: 'blur' }
  ]
})

// 获取下拉选项数据
const fetchDropdownOptions = async () => {
  try {
    const [areaRes] = await Promise.all([
      getAreaList()
    ])
    areaOptions.value = areaRes.data || []
  } catch (error) {
    console.error('获取下拉选项失败:', error)
    ElMessage.error('获取下拉选项失败')
  }
}

// 获取设备列表
const fetchDeviceList = async (area) => {
  try {
    const res = await getDeviceList(area)
    deviceOptions.value = res.data || []
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error('获取设备列表失败')
  }
}

// 获取盘点列表
const fetchInventoryList = async () => {
  try {
    loading.value = true
    const res = await listInventoryPlan(queryParams)
    inventoryList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取盘点列表失败:', error)
    ElMessage.error('获取盘点列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchInventoryList()
}

// 重置查询
const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.planNumber = ''
  queryParams.taskName = ''
  queryParams.area = ''
  queryParams.status = undefined
  fetchInventoryList()
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchInventoryList()
}

// 当前页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  fetchInventoryList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增按钮
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '新增盘点'

  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }

  Object.assign(form, {
    id: undefined,
    taskName: '',
    area: '',
    planTime: '',
    manager: '',
    deviceList: [],
    remark: ''
  })

  deviceOptions.value = []
}

// 编辑按钮
const handleEdit = async (row) => {
  try {
    const res = await getInventoryPlanDetail(row.id)
    Object.assign(form, {
      id: res.data.id,
      taskName: res.data.taskName,
      area: res.data.area,
      planTime: res.data.planTime,
      manager: res.data.manager,
      deviceList: res.data.deviceList.map(item => item.id),
      remark: res.data.remark
    })

    // 获取该区域的设备列表
    await fetchDeviceList(res.data.area)

    dialog.visible = true
    dialog.title = '编辑盘点'
  } catch (error) {
    console.error('获取盘点详情失败:', error)
    ElMessage.error('获取盘点详情失败')
  }
}

// 查看详情
const handleView = async (row) => {
  try {
    const res = await getInventoryPlanDetail(row.id)
    detailDialog.data = res.data
    detailDialog.visible = true
  } catch (error) {
    console.error('获取盘点详情失败:', error)
    ElMessage.error('获取盘点详情失败')
  }
}

// 完成盘点
const handleComplete = (row) => {
  completeForm.id = row.id
  completeForm.auditResult = ''
  completeDialog.visible = true
}

// 提交完成表单
const submitCompleteForm = async () => {
  try {
    await completeFormRef.value.validate()

    await completeInventoryPlan(completeForm)
    ElMessage.success('盘点完成')
    completeDialog.visible = false
    fetchInventoryList()
  } catch (error) {
    console.error('完成盘点失败:', error)
  }
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除盘点计划 "${row.planNumber}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return deleteInventoryPlan(row.id)
  }).then(() => {
    ElMessage.success('删除成功')
    fetchInventoryList()
  }).catch(() => { })
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (form.id) {
      await updateInventoryPlan(form)
    } else {
      await addInventoryPlan(form)
    }

    ElMessage.success('操作成功')
    dialog.visible = false
    fetchInventoryList()
  } catch (error) {
    console.error('保存盘点信息失败:', error)
  }
}

// 区域变化事件
const handleAreaChange = (area) => {
  if (area) {
    fetchDeviceList(area)
  } else {
    deviceOptions.value = []
  }
}

// 初始化加载数据
onMounted(() => {
  fetchDropdownOptions()
  fetchInventoryList()
  getEquipmentTypeList().then((res) => {
    equipmentTypeOptions.value = res.data
  })
})
</script>

<style scoped>
/* 设备清单容器样式 */
.device-transfer-container {
  display: flex;
  width: 100%;
  justify-content: space-between;
  align-items: center;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  background-color: #f5f7fa;
}

.device-list {
  width: 45%;
  height: 300px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

.device-list-header {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.device-list-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

/* 设备项样式 */
.device-item {
  display: block;
  margin: 5px 0;
  padding: 5px;
  border-radius: 4px;
}

.device-item:hover {
  background-color: #f5f7fa;
}

/* 已选设备项样式 */
.selected-device-item {
  padding: 8px;
  margin: 5px 0;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-device-item:hover {
  background-color: #f5f7fa;
}

.remove-icon {
  cursor: pointer;
  color: #f56c6c;
}

.remove-icon:hover {
  color: #ff0000;
}

/* 转移按钮样式 */
.transfer-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 120px;
  padding:0 10px;
}

.transfer-buttons .el-button {
  width: 36px;
  height: 36px;
  padding: 0;
}
</style>